<template>
  <div class="main">
    <el-row :gutter="15">
      <el-col :span="24" style="height: 84vh;display: inline-block;">
        <el-card class="leftBox">
          <div slot="header">
            <el-button type="primary" @click="toAdd" v-permission="permission.add" :disabled="handleCheckboxRows === null">新增</el-button>
            <el-button type="success" @click="toEdit" v-permission="permission.edit" :disabled="!btnStatus">修改</el-button>
            <el-button type="danger" @click="toDel" v-permission="permission.del" :disabled="!btnStatus">删除</el-button>
          </div>
          <el-card>
            <div slot="header">
              素材类型管理
            </div>
            <div class="selectArea">
              <el-tree
                ref="treeone"
                :data="optionsType"
                :expand-on-click-node="false"
                node-key="mat_type_id"
                :default-expanded-keys="[1]"
                :props="{ children: 'children', label: 'mat_type_name' }"
                @node-click="handleTypeClick">
                  <span class="custom-tree-node" slot-scope="{ node }">
                    <span style="margin-right: 30px;">{{ node.label }} </span>
                    <transition name="el-fade-in">
                      <span v-if="(node.key === handleCheckboxRows.key && node.key !== 1)">
                        <el-button
                          icon="el-icon-plus"
                          style="color: #fff;"
                          type="text"
                          size="mini"
                          v-permission="permission.add"
                          @click="toAdd">
                        </el-button>
                        <el-button
                          icon="el-icon-edit"
                          style="color: #fff;"
                          type="text"
                          size="mini"
                          v-permission="permission.edit"
                          @click="toEdit">
                        </el-button>
                        <el-button
                          icon="el-icon-delete"
                          style="color: #fff;"
                          type="text"
                          size="mini"
                          v-permission="permission.del"
                          @click="toDel">
                        </el-button>
                      </span>
                    </transition>
                  </span>
              </el-tree>
            </div>
          </el-card>
          <!--表单组件-->
          <el-dialog
            append-to-body
            :close-on-click-modal="false"
            :before-close="cancelCU"
            :visible.sync="dialogInfo.cu > 0"
            width="500px"
            :title="dialogInfo.title">
            <el-form ref="form" inline :model="form" :rules="rules" label-width="80px">
              <el-form-item label="父类型">
                <el-input v-model="form.parent_type_name" class="elInputS" disabled />
              </el-form-item>
              <el-form-item label="类型名">
                <el-input v-model="form.mat_type_name" class="elInputS" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="form.remark" class="elInputS" />
              </el-form-item>
              <el-form-item label="操作用户">
                <el-cascader
                    class="elInputM"
                    v-model="form.oper_rights"
                    :options="usersList"
                    :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'username' }"
                    clearable>
                </el-cascader>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="cancelCU">取消</el-button>
              <el-button :loading="dialogInfo.cu === 3" type="primary" @click="submitCU">确认</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 配置表单字段默认值
import { matTlist, matTadd, matTedit, matTdel } from '@/api/material/mattype.js'
import commonMethods from '@/utils/commonMethods.js'
const defaultForm = { parent_type: 0, parent_type_name: '根类型', mat_type_name: '', oper_rights: [], remark: '' }
export default {
  name: 'Mattype',
  mixins: [commonMethods],
  created() {
    this.getmatTypeList()
  },
  methods: {
    handleTypeClick(data, node, el) {
      this.handleCheckboxRows = node
      this.currCheckKey = node.key
    },
    // 取消
    cancelCU() {
      this.dialogInfo.cu = 0
      this.form = JSON.parse(JSON.stringify(defaultForm))
    },
    // 提交
    submitCU() {
      if (this.dialogInfo.cu === 1) { // 新增
        matTadd(this.form).then((res) => {
          if (res.status === 200) {
            this.$refs.treeone.append(JSON.parse(JSON.stringify(this.form)), this.handleCheckboxRows)
            this.$message.success('新增成功')
          }
          this.cancelCU()
        })
      } else { // 编辑
        this.dialogInfo.cu = 2
        matTedit(this.form).then((res) => {
          if (res.status === 200) {
            this.handleCheckboxRows.data = this.form
            this.$refs.treeone.updateKeyChildren(this.handleCheckboxRows.key, this.handleCheckboxRows)
            this.$message.success('新增成功')
          }
          this.cancelCU()
        })
      }
    },
    toAdd() {
      this.getUserList()
      this.dialogInfo.cu = 1
      this.dialogInfo.title = '新增素材类型参数'
      this.form.parent_type = this.handleCheckboxRows.key || defaultForm.parent_type
      this.form.parent_type_name = this.handleCheckboxRows.label || defaultForm.parent_type_name
      this.form.mat_type_name = ''
      this.form.oper_rights = []
      this.form.remark = ''
    },
    toEdit() {
      this.getUserList()
      this.dialogInfo.cu = 2
      this.dialogInfo.title = '编辑素材类型参数'
      this.form = JSON.parse(JSON.stringify(this.handleCheckboxRows.data))
    },
    async toDel() {
      const confirmresult = await this.$confirm('是否删除素材类型`' + this.handleCheckboxRows.label + '` 及其下所有子类型， 该操作执行后不可撤销，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }
      // console.log(this.findNodeChildValArr(this.handleCheckboxRows, 'key', [], 'childNodes'))
      const ids = this.findNodeChildValArr(this.handleCheckboxRows, 'key', [], 'childNodes')
      if (ids.length > 0) {
        matTdel(ids).then(res => {
          if (res.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.$message.success('删除成功')
          this.$refs.treeone.remove(this.handleCheckboxRows)
        })
      }
    },
    getmatTypeList() {
      matTlist().then(res => {
        if (res.status !== 200) {
          console.log('获取失败')
        }
        this.optionsType = res.data.data
      })
    },
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: {
          pagenum: 1,
          pagesize: 999
        }
      })
      this.usersList = res.data.users
    }
  },
  computed: {
    btnStatus() {
      return this.handleCheckboxRows !== null && this.currCheckKey > 1
    }
  },
  data() {
    return {
      /* 设置页面权限 */
      permission: {
        add: ['admin', 'mattype::add'],
        edit: ['admin', 'mattype::edit'],
        del: ['admin', 'mattype::delete']
      },
      activeName: '1',
      currCheckKey: 0,
      handleCheckboxRows: {
        key: 0
      },
      form: defaultForm,
      // 表单验证规则
      rules: {},
      dialogInfo: {
        title: '新增素材类型参数',
        cu: 0
      },
      usersList: [],
      optionsType: []
    }
  }
}
</script>

<style lang="less" scoped>
  #DeviceBox .el-card__header {
    background-color: #fff;
  }
  .operator {
    float: right;
    display: inline-block;
    margin-left: 20px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
</style>
